<template>
  <div class="app-container">
    <!-- 查询 -->
    <tl-list-search ref="search" style="margin:6px 0" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false" v-if="isHeaderDisplay">
      <template slot="search">
        <el-form-item label="申请人" class="qryItem" style="margin-left:-14px">
          <el-input v-model="queryParam.qry_user" placeholder="工号或姓名"></el-input>
        </el-form-item>
        <el-form-item label="单据状态" class="qryItem">
          <el-select v-model="queryParam.qry_state" clearable placeholder="请选择单据状态">
            <el-option v-for="item in codeModel.stateList" :key="item.code" :label="item.name" :value="item.code" clearable />
          </el-select>
        </el-form-item>
      </template>
    </tl-list-search>
    <!-- 工具栏 -->
    <tl-list-toolbar class="tl-list-toolbar" :refMainTable="$refs.mainTable" currentModuleTableCode="mpmProjectDemand/main" :startColumn="3" ref="toolbar" @add="openAddDialog('editForm')" @deleteBatch="doDeleteBatch" @exportExcel="doExportExcel" @refresh="doRefreshApproval" @columnCustomize="doColumnCustomize" @displaySearch="doDisplaySearch" :disableDeleteBatch="selectedRowKeys.length <= 0" :isDisplayDeleteBatch="false" :isDisplayAdd="false">
      <template slot="left-btn"> </template>
    </tl-list-toolbar>
    <div>
      <!-- 列表选择 -->
      <div class="table-alert-div" ref="selector">
        <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
          <template slot="title">
            已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRowKeys.length }}</a
            >项&nbsp;&nbsp;
            <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
          </template>
        </el-alert>
      </div>
      <!--表格渲染-->
      <el-table class="tl-table" ref="mainTable" :height="tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datasTemp" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" @row-click="doRowClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
        <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
        <el-table-column prop="ordercode" label="编号" width="130px" sortable="custom" sort-by="ordercode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispstate" label="状态" width="100px" sortable="custom" sort-by="state" align="center" header-align="center" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <el-tag :type="changeStateType(scope.row.state)">
              {{ scope.row.dispstate }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="latestphase" label="最新阶段" width="200px" sortable="custom" sort-by="latestphase" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="demanddescription" label="需求描述" width="200px" sortable="custom" sort-by="demanddescription" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="demandsource" label="需求来源" width="150px" sortable="custom" sort-by="demandsource" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="demanddate" label="需求日期" width="100px" sortable="custom" sort-by="demanddate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="spincharge" label="责任人" width="150px" sortable="custom" sort-by="incharge" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="incharge" label="责任人工号" width="100px" sortable="custom" sort-by="incharge" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispdemandstate" label="需求状态" width="100px" sortable="custom" sort-by="demandstate" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="username" label="申请人姓名" width="120px" sortable="custom" sort-by="username" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="usercode" label="申请人工号" width="100px" sortable="custom" sort-by="usercode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="projectname" label="项目名称" width="250px" sortable="custom" sort-by="projectname" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispprojectlevel" label="项目级别" width="100px" sortable="custom" sort-by="projectlevel" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="projectmanager" label="项目经理" width="100px" sortable="custom" sort-by="projectmanager" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="projectmanagercode" label="项目经理工号" width="120px" sortable="custom" sort-by="projectmanagercode" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="spdistribute" label="分发人员" width="200px" sortable="custom" sort-by="distribute" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispdistributecode" label="分发人员工号" width="120px" sortable="custom" sort-by="distribute" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="docdate" label="单据日期" width="150px" sortable="custom" sort-by="docdate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="submitdate" label="提交日期" width="150px" sortable="custom" sort-by="submitdate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="description" label="备注" min-width="250px" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="100px" v-slot="scope" fixed="right">
          <el-dropdown trigger="hover">
            <el-button type="text" icon="el-icon-s-operation" style="margin-left: 10px">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-view" @click.native="openViewDialog('editForm', scope.row.id)">查看</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </el-table>
      <!-- 列表分页 -->
      <el-row class="pagebar" ref="pager">
        <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
      </el-row>
      <tl-edit ref="editForm" @refresh="doRefreshApproval" :projectinfo="projectinfo"></tl-edit>
      <tl-approval ref="approvalForm" @refresh="doRefreshApproval"></tl-approval>
    </div>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
/** 子组件 */
import tlApproval from '@/views/cbo/cboApprovalNodeIns/approvalOne'
import tlEdit from './edit'
/** API */
import { checkPermission } from '@tapui/utils/permission'
/** 工具类 */
import { getAction, putAction, postAction, deleteAction } from '@tapui/utils/http'
import { exportExcelAxio } from '@tapui/api/office'
export default {
  name: 'mpmProjectDemand',
  mixins: [mixin_list],
  components: { tlEdit, tlApproval },
  data() {
    return {
      description: '项目需求-列表查询',
      urlPrefix: '/mpm/projectDemand/',
      url: {
        queryCodeList: '/mpm/projectDemand/dataCodeList',
        queryApprovalList: '/cbo/approvalNodeIns/queryApprovalList'
      },
      reduceHeight: 264,
      // 排序参数
      sorterInfo: {
        // sidx: 'sortcode',
        sidx: 'state',
        sord: 'asc'
      },
      sourceList: [],
      datasTemp: [],
      countApproval: 0,
      approvalDataList: [],
      sourcetype: 'MpmProjectDemand'
    }
  },
  props: {
    // 从父组件中得到该项目的相关信息
    projectinfo: {
      type: Object,
      default() {
        return {}
      }
    },
    // 来自于哪个index组件
    fromIndexType: {
      type: String,
      default: ''
    }
  },
  methods: {
    /** 重写导出Excel方法 */
    doExportExcel() {
      if (!this.beforeExportData()) return
      let cols = []
      this.$refs.mainTable.$children.forEach((col) => {
        if (col.$options._componentTag === 'el-table-column') {
          if (col.$options.propsData.prop && col.$options.propsData.label !== '待处理') {
            cols.push(col.$options.propsData.prop + ';' + col.$options.propsData.label)
          }
        }
      })
      let qry_id = []
      this.selectedRowKeys.forEach((key) => {
        qry_id.push("'" + key + "'")
      })
      let url = this.url.exportExcel
      let data = {}
      Object.assign(data, this.getQueryParams(), { cols: cols.join(',') }, { qry_id: qry_id.join(',') })
      exportExcelAxio({ url: url, data: data })
        .then((res) => {
          var reader = new FileReader()
          reader.readAsText(res.data, 'utf-8')
          reader.onload = () => {
            try {
              var info = JSON.parse(reader.result)
              this.$tap.alert(info.message)
            } catch (e) {
              var isTaskExport = res.headers.istaskexport
              if (isTaskExport === '1') {
                this.$tap.alert('系统正在导出，请到excel导出任务页面下载')
              } else {
                var blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' })
                var filename = decodeURI(res.headers['filename'])
                if (typeof filename === 'undefined') {
                  filename = '导出数据.xlsx'
                }
                var tempObjectUrl = window.URL.createObjectURL(blob)
                var aLink = document.createElement('a')
                aLink.style.display = 'none'
                aLink.download = filename
                aLink.href = tempObjectUrl
                document.body.appendChild(aLink)
                aLink.click()
                document.body.removeChild(aLink)
                window.URL.revokeObjectURL(tempObjectUrl)
                this.afterExportData()
              }
            }
          }
        })
        .catch((error) => {
          this.$tap.alert(error, 'warning')
        })
    },
    // 提交审批单后重加载项目需求右上方小红点
    doRefreshApproval() {
      this.loadData({})
      this.$emit('refreshIndex')
    },
    // 打开审批单页面
    openApprovalDialog(id) {
      this.$refs.approvalForm.nodeInsId = id
      this.$refs.approvalForm.visible = true
    },
    // 双击表格中的一行触发事件
    doRowDbClick(row, column, event) {
      this.openViewDialog('editForm', row[this.$refs.mainTable.rowKey])
    },
    // loadData前加载
    beforeLoadData() {
      if (!this.projectinfo) {
        return false
      }
      // 默认查询条件设置
      this.queryParam.qry_projectcode = this.projectinfo.projectcode
      return true
    },
    // loadData()后执行，重排序datas数据，将审批单内容置顶
    afterLoadData() {
      const param = {
        qry_sourcetype: 'MpmProjectDemand'
      }
      var count = 0
      // get请求获取该用户此项目的审批单信息
      getAction(this.url.queryApprovalList, param).then((res) => {
        if (res.success) {
          this.datasTemp = []
          var sourceidArr = []
          var datasNoApproval = []
          this.sourceList = res.result.dataList
          this.sourceList.forEach((source) => {
            sourceidArr.push(source.sourceid)
          })
          this.datas.forEach((data) => {
            if (sourceidArr.indexOf(data.id) > -1) {
              this.datasTemp.push(data)
            } else {
              datasNoApproval.push(data)
            }
          })
          this.datasTemp = this.datasTemp.concat(datasNoApproval)
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    isInApprovalList(row) {
      return this.sourceList.filter((item) => item.sourceid === row.id).length > 0
    },
    /** 改变审核状态标签颜色 */
    changeStateType(state) {
      return state === 0 ? 'info' : state === 2 ? 'danger' : state === 9 ? 'success' : ''
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  margin: 0;
}
</style>
